package com.salim.leetcode.$33;

import lombok.extern.slf4j.Slf4j;

/**
 * https://www.cnblogs.com/grandyang/p/4325648.html
 */
@Slf4j
public class SearchInRotatedSortedArray {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[mid] < nums[right]) {
                if (nums[mid] < target && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            } else {
                if (nums[left] <= target && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        SearchInRotatedSortedArray s = new SearchInRotatedSortedArray();
        log.info("SearchInRotatedSortedArray输出结果1：{}", s.search(new int[]{4, 5, 6, 7, 0, 1, 2}, 0));
        log.info("SearchInRotatedSortedArray输出结果2：{}", s.search(new int[]{4, 5, 6, 7, 0, 1, 2}, 3));
        log.info("SearchInRotatedSortedArray输出结果3：{}", s.search(new int[]{1}, 0));
    }
}
